#!/usr/bin/python
# Copyright (c) 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tools for using Make to build bionic projects such as libc
"""

import process
import sys

from bionic_dirs import *
from file_update import Mkdir, Rmdir, Symlink, UpdateText
from replace import ReplaceArch, ReplaceText


def PnaclTool(name, arch):
  return os.path.join(OUTPUT_ROOT,'bionic_work','bin',
                      '%s-nacl-%s' % (arch,name))


def ConfigureCMake(arch, project, srcpath = None, extra_args=[]):
  srcpath = os.path.join(BIONIC_SRC, project)
  args = ['cmake', '-G', 'Unix Makefiles',
          '-DCMAKE_C_COMPILER_WORKS=1',
          '-DCMAKE_CXX_COMPILER_WORKS=1',
          '-DCMAKE_INSTALL_PREFIX=',
          '-DCMAKE_BUILD_TYPE=Release',
          '-DCMAKE_C_COMPILER=' + PnaclTool('clang', arch),
          '-DCMAKE_CXX_COMPILER=' + PnaclTool('clang++', arch),
          '-DCMAKE_SYSTEM_NAME=nacl',
          '-DCMAKE_AR=' + PnaclTool('ar', arch),
          '-DCMAKE_NM=' + PnaclTool('nm', arch),
          '-DCMAKE_RANLIB=' + PnaclTool('ranlib', arch),
          '-DCMAKE_LD=' + PnaclTool('illegal', arch),
          '-DCMAKE_AS=' + PnaclTool('as', arch),
          '-DCMAKE_OBJDUMP=' + PnaclTool('illegal', arch),
          '-DCMAKE_C_FLAGS=-std=gnu11', # FLAGS + LibCxxCflags(bias_arch),
          '-DCMAKE_CXX_FLAGS=-std=gnu++11', # FLAGS + LibCxxCflags(bias_arch),
          # '-DLIT_EXECUTABLE=' + command.path.join(
          #    '%(llvm_src)s', 'utils', 'lit', 'lit.py'),
          # The lit flags are used by the libcxx testsuite, which is
          # currenty driven by an external script.
          #'-DLLVM_LIT_ARGS=--verbose  --param shell_prefix="' +
          #os.path.join(NACL_DIR,'run.py') +' -arch env --retries=1" '+
          #'--param exe_suffix=".nexe" --param use_system_lib=true ' +
          #'--param cxx_under_test="' + os.path.join(NACL_DIR,
          #    'toolchain/linux_x86/pnacl_newlib',
          #    'bin/pnacl-clang++') +
          #'" '+
          '--param link_flags="-std=gnu++11 --pnacl-exceptions=sjlj"',
          '-DLIBCXX_ENABLE_CXX0X=0',
          '-DLIBCXX_ENABLE_SHARED=0',
          '-DLIBCXX_CXX_ABI=libcxxabi',
          '-DLIBCXX_LIBCXXABI_INCLUDE_PATHS=' + os.path.join(
            TOOLCHAIN_BUILD_DIR, 'src', 'libcxxabi', 'include'),
          srcpath
    ] + extra_args

  workpath = os.path.join(OUTPUT_ROOT, 'bionic_$GCC_work', project)
  workpath = ReplaceArch(workpath, arch)
  Mkdir(workpath)

  print "CMake libcc: " + workpath
  if process.Run(args, cwd=workpath, outfile=sys.stdout):
    raise RuntimeError('Failed to cmake %s for %s.\n' % (project, arch))
  print 'Done with %s for %s.\n' % (project, arch)
